﻿using AutoMapper;
using Finance.Api.Write.Applications.Commands.财务管理.Receives;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Security.Claims;

namespace Finance.Api.Write.Applications.CommandHands.财务管理.ReturnMonerys.Receives
{
    public class ReceiveDelLoginCommandHandler : IRequestHandler<ReceiveDelLoginCommand, ApiResult<bool>>
    {
        private readonly SqlsugarDb<Receive> db;
        private readonly IMapper mapper;
        private readonly IHttpContextAccessor httpContextAccessor;





        public ReceiveDelLoginCommandHandler(SqlsugarDb<Receive> db, IMapper mapper, IHttpContextAccessor httpContextAccessor)
        {
            this.db = db;
            this.mapper = mapper;
            this.httpContextAccessor = httpContextAccessor;
        }

        public async Task<ApiResult<bool>> Handle(ReceiveDelLoginCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<bool>();

            try
            {
                var entity = await db.FirstQuery().FirstAsync(x => x.Id == request.Id);

                if (entity == null)
                {
                    result.message = "查无数据";
                    result.Code = Enumcode.fail;
                }
                entity = mapper.Map(request, entity);
                entity.IsDelete = true;
                entity.DeleteTime = DateTime.Now;
                entity.DeleteName= httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name)?.Value;
                entity.LoginId = Convert.ToInt32(httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
                
                var delResult= await db.Updata(entity);
                if (delResult > 0)
                {
                    result.message = "收款信息逻辑删除成功";
                    result.Code = Enumcode.ok;
                    result.data = false;

                }

               
            }
            catch (Exception ex)
            {

                result.message =ex.Message;
                result.Code = Enumcode.fail;
                result.data = true;
            }
           
            return await Task.FromResult(result);
        }
    }
}
